﻿using System;
using System.Collections.Generic;
using System.Text;

namespace WPay.Infrastructure.Unity
{
    /// <summary>
    /// 校验字生成工具类
    /// 提供功能【1：生成校验字
    /// 2：验证校验字是否正确】
    /// </summary>
    public class ChkCodeTool
    {
        /// <summary>
        /// 生成校验字
        /// </summary>
        /// <param name="code"></param>
        /// <returns>返回校验字，-1表示异常</returns>
        public static int GetChkCode(string code)
        {
            try
            {
                //code = Regex.Replace(code, @"[^\d]*", "");//替换非数字
                int c1 = 0;
                int c2 = 0;
                for (int i = 0; i < code.Length; i++)
                {
                    int cTmp;
                    bool cParse = int.TryParse(code[i].ToString(), out cTmp);
                    if (!cParse)//如果不是数字，则跳过本次循环进入下一次
                        continue;
                    if (i % 2 == 0)
                        c1 += cTmp;
                    else
                        c2 += cTmp;
                }
                int cc = (c1 + c2 * 3) % 10;
                int c = 10 - cc;
                if (c == 10)
                    c = 0;
                return c;
            }
            catch (Exception)
            {
                return 0;
            }
        }
        /// <summary>
        /// 验证校验字是否正确
        /// </summary>
        /// <param name="code">含校验字的字符串</param>
        /// <returns>true正确；false错误</returns>
        public static bool VerifyChkCode(string code)
        {
            try
            {

                if (string.IsNullOrEmpty(code) || code.Length < 2)
                    return false;
                //截取原字符串
                string strCode = code.Substring(0, code.Length - 1);
                //生成校验字
                int getChkCode = GetChkCode(strCode);
                //截取校验字
                string chkCodeStr = code.Substring(code.Length - 1, 1);
                int chkCode = 0;
                bool parse = int.TryParse(chkCodeStr, out chkCode);
                if (!parse)
                    return false;
                //判断校验字是否正确
                return getChkCode == chkCode;

            }
            catch (Exception )
            {
                return false;
            }
        }
    }
}
